package com.uwlaser.service.impl;

import com.baidubce.services.ros.model.Capacity;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.uwlaser.domain.CraftParamDetail;
import com.uwlaser.service.dto.CheckGearResult;
import com.uwlaser.service.dto.GetCapacityByProductSnParam;
import com.uwlaser.service.mapper.CraftParamDetailMapper;
import com.uwlaser.service.mapper.ProductModelMapper;
import com.uwlaser.utils.SecurityUtils;
import lombok.AllArgsConstructor;
import com.uwlaser.base.PageInfo;
import com.uwlaser.base.QueryHelpMybatisPlus;
import com.uwlaser.base.impl.CommonServiceImpl;
import com.uwlaser.utils.ConvertUtil;
import com.uwlaser.utils.PageUtil;
import com.uwlaser.domain.DataCellCapacity;
import com.uwlaser.service.DataCellCapacityService;
import com.uwlaser.service.dto.DataCellCapacityDto;
import com.uwlaser.service.dto.DataCellCapacityQueryParam;
import com.uwlaser.service.mapper.DataCellCapacityMapper;
import org.apache.ibatis.exceptions.TooManyResultsException;
import org.mybatis.spring.MyBatisSystemException;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
// 默认不使用缓存
//import org.springframework.cache.annotation.CacheConfig;
//import org.springframework.cache.annotation.CacheEvict;
//import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.domain.Pageable;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author caoguilin
* @date 2023-02-06
*/
@Service
@AllArgsConstructor
// @CacheConfig(cacheNames = DataCellCapacityService.CACHE_KEY)
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class DataCellCapacityServiceImpl extends CommonServiceImpl<DataCellCapacityMapper, DataCellCapacity> implements DataCellCapacityService {

    // private final RedisUtils redisUtils;
    private final DataCellCapacityMapper dataCellCapacityMapper;

    private final CraftParamDetailMapper craftParamDetailMapper;

    @Override
    public PageInfo<DataCellCapacityDto> queryAll(DataCellCapacityQueryParam query, Pageable pageable) {
        IPage<DataCellCapacity> queryPage = PageUtil.toMybatisPage(pageable);
        IPage<DataCellCapacity> page = dataCellCapacityMapper.selectPage(queryPage, QueryHelpMybatisPlus.getPredicate(query));
        return ConvertUtil.convertPage(page, DataCellCapacityDto.class);
    }

    @Override
    public List<DataCellCapacityDto> queryAll(DataCellCapacityQueryParam query){
        return ConvertUtil.convertList(dataCellCapacityMapper.selectList(QueryHelpMybatisPlus.getPredicate(query)), DataCellCapacityDto.class);
    }

    @Override
    public DataCellCapacity getById(Integer id) {
        return dataCellCapacityMapper.selectById(id);
    }

    @Override
    // @Cacheable(key = "'id:' + #p0")
    public DataCellCapacityDto findById(Integer id) {
        return ConvertUtil.convert(getById(id), DataCellCapacityDto.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(DataCellCapacityDto resources) {
        DataCellCapacity entity = ConvertUtil.convert(resources, DataCellCapacity.class);
        DataCellCapacity dataCellCapacity=new DataCellCapacity();
        dataCellCapacity.setProductSn(resources.getProductSn());
        Integer integer = dataCellCapacityMapper.selectCount(new QueryWrapper<>(dataCellCapacity));
        if(integer>0){
            throw new RuntimeException("条码:"+resources.getProductSn()+"已经存在容量数据!");
        }
        return dataCellCapacityMapper.insert(entity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateById(DataCellCapacityDto resources){
        DataCellCapacity entity = ConvertUtil.convert(resources, DataCellCapacity.class);
        int ret = dataCellCapacityMapper.updateById(entity);
        // delCaches(resources.id);
        return ret;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeByIds(Set<Integer> ids){
        // delCaches(ids);
        return dataCellCapacityMapper.deleteBatchIds(ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeById(Integer id){
        Set<Integer> set = new HashSet<>(1);
        set.add(id);
        return this.removeByIds(set);
    }

    /*
    private void delCaches(Integer id) {
        redisUtils.delByKey(CACHE_KEY + "::id:", id);
    }

    private void delCaches(Set<Integer> ids) {
        for (Integer id: ids) {
            delCaches(id);
        }
    }*/

    /*
    @Override
    public void download(List<DataCellCapacityDto> all, HttpServletResponse response) throws IOException {
      List<Map<String, Object>> list = new ArrayList<>();
      for (DataCellCapacityDto dataCellCapacity : all) {
        Map<String,Object> map = new LinkedHashMap<>();
              map.put("电芯条码", dataCellCapacity.getProductSn());
              map.put("电芯容量", dataCellCapacity.getCapacity());
              map.put("创建人", dataCellCapacity.getCreateBy());
              map.put("创建时间", dataCellCapacity.getCreateTime());
              map.put("更新人", dataCellCapacity.getUpdateBy());
              map.put("更新时间", dataCellCapacity.getUpdateTime());
        list.add(map);
      }
      FileUtil.downloadExcel(list, response);
    }*/

    @Override
    public int importCellCapacityBatch(List<DataCellCapacityDto> dataCellCapacityDtoList) {
        DataCellCapacity dataCellCapacity=new DataCellCapacity();
        List<DataCellCapacityDto> newCapacityDataList=new ArrayList<>();
        //根据条码分组
        try{
            Map<String, List<DataCellCapacityDto>> groupList = dataCellCapacityDtoList.stream().collect(Collectors.groupingBy(DataCellCapacityDto::getProductSn));
            if(groupList.size()!=dataCellCapacityDtoList.size()){
                throw new RuntimeException("导入的Excel数据表中存在重复数据");
            }
        }catch (Exception e){
            if(e instanceof NullPointerException) throw new RuntimeException("解析数据表异常，请检查数据表格式是否正确！");
            throw e;
        }
        //迭代集合查询是否存在已有的容量数据
        for (DataCellCapacityDto dataCellCapacityDto : dataCellCapacityDtoList) {
            //查询库中是否存在，如果存在此电芯的档位数据那么将跳过此条记录上传
            dataCellCapacity.setProductSn(dataCellCapacityDto.getProductSn());
            Integer integer = dataCellCapacityMapper.selectCount(new QueryWrapper<>(dataCellCapacity));
            if(integer!=0)  throw new RuntimeException(dataCellCapacityDto.getProductSn()+"已存在容量数据!");

            dataCellCapacityDto.setCreateBy(SecurityUtils.getCurrentUsername());
            dataCellCapacityDto.setCreateTime(new Date());
            newCapacityDataList.add(dataCellCapacityDto);


        }
        return  dataCellCapacityMapper.importCellCapacityBatch(newCapacityDataList);
    }

    @Override
    public DataCellCapacityDto getCapacityByProductSn(GetCapacityByProductSnParam param) {
        try {
            DataCellCapacityDto capacity = dataCellCapacityMapper.getCapacity(param);
            return capacity;
        }catch (Exception e){
            throw new RuntimeException("["+param.getProductSn()+"]此电芯存在多个容量数据，请查验！");
        }
    }

    @Override
    public CheckGearResult checkGear(GetCapacityByProductSnParam param) {
        //校验结果对象
        CheckGearResult result=new CheckGearResult();

        //获取产品型号
        String productCode = param.getProductCode();

        //根据产品型号查询MES配置的档位信息
        CraftParamDetail gearData = craftParamDetailMapper.selectGearData(productCode);
        //如果档位信息配置为OFF，则说明关闭了档位校验，默认返回OK
        if("OFF".equals(gearData.getStandard())){
            //档位校验关闭
            result.setGear(gearData.getStandard());
            result.setMsg("MES已关闭档位校验！");
            result.setResult(200);
            return result;
        }
        if(gearData==null){
            //未导入档位信息
            result.setProductSn(param.getProductSn());
            result.setMsg("产品型号:["+productCode+"]在MES无档位信息，请检查工艺参数配置!");
            result.setResult(400);
            return result;
        }

        DataCellCapacity capacity=new DataCellCapacity();
        capacity.setProductSn(param.getProductSn());
        //根据电芯码查询库中的档位、容量数据
        try{
            DataCellCapacity localGearData = dataCellCapacityMapper.selectOne(new QueryWrapper<>(capacity));
            if(localGearData!=null){
                if(gearData.getStandard().equals(localGearData.getGear())){
                    result.setGear(localGearData.getGear());
                    result.setCapacity(localGearData.getCapacity());
                    result.setProductSn(localGearData.getProductSn());
                    result.setResult(200);
                }else {
                    //档位和MES配置不符
                    result.setProductSn(param.getProductSn());
                    result.setGear(localGearData.getGear());
                    result.setCapacity(localGearData.getCapacity());
                    result.setMsg("产品条码["+param.getProductSn()+"]档位为["+localGearData.getGear()+"],MES配置的档位为["+gearData.getStandard()+"]，档位校验NG！");
                    result.setResult(400);
                }
            }else {
                result.setProductSn(param.getProductSn());
                result.setMsg("MES中不存在["+param.getProductSn()+"]此产品的档位数据，请先上传后再进行操作！");
                result.setResult(400);
            }
        }catch (Exception e){
            if(e instanceof MyBatisSystemException) {
                throw new RuntimeException("["+param.getProductSn()+"]产品条码存在多个档位数据，请查验后重试!");
            }else {
                throw e;
            }
        }
        return result;
    }
}
